$(function() {
    // 初始化图表
    var temperatureChart = echarts.init(document.getElementById('temperatureChart'));
    var humidityChart = echarts.init(document.getElementById('humidityChart'));
    var abnormalChart = echarts.init(document.getElementById('abnormalChart'));
    
    // 初始化日期选择器
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayBtn: 'linked',
        language: 'zh-CN',
        todayHighlight: true
    });
    
    // 设置默认日期范围（最近7天）
    var today = new Date();
    var lastWeek = new Date();
    lastWeek.setDate(today.getDate() - 7);
    
    $('#startDateInput').datepicker('setDate', lastWeek);
    $('#endDateInput').datepicker('setDate', today);
    
    // 加载仓库下拉框选项
    loadWarehouseOptions();
    
    // 仓库选择变更事件
    $('#warehouseSelect').on('change', function() {
        var warehouseId = $(this).val();
        if (warehouseId) {
            loadStorageAreas(warehouseId);
        } else {
            $('#storageAreaSelect').html('<option value="">全部区域</option>');
            $('#deviceIdSelect').html('<option value="">全部设备</option>');
        }
    });
    
    // 区域选择变更事件
    $('#storageAreaSelect').on('change', function() {
        var warehouseId = $('#warehouseSelect').val();
        var storageArea = $(this).val();
        if (warehouseId && storageArea) {
            loadDeviceIds(warehouseId, storageArea);
        } else {
            $('#deviceIdSelect').html('<option value="">全部设备</option>');
        }
    });
    
    // 查询按钮点击事件
    $('#searchBtn').on('click', function() {
        searchTrendData();
    });
    
    // 重置按钮点击事件
    $('#resetBtn').on('click', function() {
        $('#storageAreaSelect').html('<option value="">全部区域</option>');
        $('#deviceIdSelect').html('<option value="">全部设备</option>');
        $('#aggregateTypeSelect').val('hour');
        
        // 重置日期为最近7天
        var today = new Date();
        var lastWeek = new Date();
        lastWeek.setDate(today.getDate() - 7);
        
        $('#startDateInput').datepicker('setDate', lastWeek);
        $('#endDateInput').datepicker('setDate', today);
        
        // 清空图表
        temperatureChart.clear();
        humidityChart.clear();
        abnormalChart.clear();
    });
    
    // 窗口大小变化时，重新调整图表大小
    window.addEventListener('resize', function() {
        temperatureChart.resize();
        humidityChart.resize();
        abnormalChart.resize();
    });
    
    // 加载仓库选项
    function loadWarehouseOptions() {
        $.ajax({
            url: '/warehouse/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var options = '';
                    $.each(res.data, function(index, warehouse) {
                        options += '<option value="' + warehouse.warehouseId + '">' + warehouse.warehouseName + '</option>';
                    });
                    $('#warehouseSelect').append(options);
                    
                    // 如果有仓库，默认选中第一个并加载区域
                    if (res.data && res.data.length > 0) {
                        $('#warehouseSelect').val(res.data[0].warehouseId).trigger('change');
                    }
                }
            }
        });
    }
    
    // 加载区域选项
    function loadStorageAreas(warehouseId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/latest/' + warehouseId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var areas = [];
                    var options = '<option value="">全部区域</option>';
                    
                    // 提取不重复的区域
                    $.each(res.data, function(index, monitor) {
                        if (monitor.storageArea && !areas.includes(monitor.storageArea)) {
                            areas.push(monitor.storageArea);
                            options += '<option value="' + monitor.storageArea + '">' + monitor.storageArea + '</option>';
                        }
                    });
                    
                    $('#storageAreaSelect').html(options);
                }
            }
        });
    }
    
    // 加载设备ID选项
    function loadDeviceIds(warehouseId, storageArea) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/latest/' + warehouseId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var deviceIds = [];
                    var options = '<option value="">全部设备</option>';
                    
                    // 提取不重复的设备ID
                    $.each(res.data, function(index, monitor) {
                        if (monitor.storageArea === storageArea && monitor.deviceId && !deviceIds.includes(monitor.deviceId)) {
                            deviceIds.push(monitor.deviceId);
                            options += '<option value="' + monitor.deviceId + '">' + monitor.deviceId + '</option>';
                        }
                    });
                    
                    $('#deviceIdSelect').html(options);
                }
            }
        });
    }
    
    // 查询趋势数据
    function searchTrendData() {
        var warehouseId = $('#warehouseSelect').val();
        if (!warehouseId) {
            alert('请选择仓库！');
            return;
        }
        
        var startDate = $('#startDateInput').val();
        var endDate = $('#endDateInput').val();
        if (!startDate || !endDate) {
            alert('请选择查询时间范围！');
            return;
        }
        
        var startDateTime = startDate + ' 00:00:00';
        var endDateTime = endDate + ' 23:59:59';
        
        var storageArea = $('#storageAreaSelect').val();
        var deviceId = $('#deviceIdSelect').val();
        var aggregateType = $('#aggregateTypeSelect').val();
        
        // 构建查询参数
        var params = {
            warehouseId: warehouseId,
            startTime: startDateTime,
            endTime: endDateTime
        };
        
        if (storageArea) {
            params.storageArea = storageArea;
        }
        
        if (deviceId) {
            params.deviceId = deviceId;
        }
        
        // 根据聚合方式选择API
        var url = '/warehouse/coldStorageMonitor/trend/' + aggregateType;
        
        // 发送请求
        $.ajax({
            url: url,
            type: 'GET',
            data: params,
            success: function(res) {
                if (res.code === 200) {
                    renderCharts(res.data, aggregateType);
                } else {
                    alert('查询失败：' + res.msg);
                }
            },
            error: function() {
                alert('查询失败，请稍后重试！');
            }
        });
    }
    
    // 渲染图表
    function renderCharts(data, aggregateType) {
        if (!data || data.length === 0) {
            alert('没有查询到数据！');
            return;
        }
        
        // 提取时间点
        var timePoints = data.map(function(item) {
            return item.time_point;
        });
        
        // 提取温度数据
        var avgTemperature = data.map(function(item) {
            return item.avg_temperature;
        });
        var maxTemperature = data.map(function(item) {
            return item.max_temperature;
        });
        var minTemperature = data.map(function(item) {
            return item.min_temperature;
        });
        
        // 提取湿度数据
        var avgHumidity = data.map(function(item) {
            return item.avg_humidity;
        });
        var maxHumidity = data.map(function(item) {
            return item.max_humidity;
        });
        var minHumidity = data.map(function(item) {
            return item.min_humidity;
        });
        
        // 渲染温度趋势图
        var temperatureOption = {
            title: {
                text: '温度趋势',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    var result = params[0].name + '<br/>';
                    params.forEach(function(param) {
                        result += param.seriesName + ': ' + param.value + ' °C<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: ['平均温度', '最高温度', '最低温度'],
                bottom: 10
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: timePoints,
                axisLabel: {
                    rotate: 30
                }
            },
            yAxis: {
                type: 'value',
                name: '温度(°C)',
                axisLabel: {
                    formatter: '{value} °C'
                }
            },
            series: [
                {
                    name: '平均温度',
                    type: 'line',
                    data: avgTemperature,
                    markPoint: {
                        data: [
                            {type: 'max', name: '最大值'},
                            {type: 'min', name: '最小值'}
                        ]
                    }
                },
                {
                    name: '最高温度',
                    type: 'line',
                    data: maxTemperature,
                    lineStyle: {
                        type: 'dashed'
                    }
                },
                {
                    name: '最低温度',
                    type: 'line',
                    data: minTemperature,
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            ]
        };
        
        // 渲染湿度趋势图
        var humidityOption = {
            title: {
                text: '湿度趋势',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    var result = params[0].name + '<br/>';
                    params.forEach(function(param) {
                        result += param.seriesName + ': ' + param.value + ' %<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: ['平均湿度', '最高湿度', '最低湿度'],
                bottom: 10
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: timePoints,
                axisLabel: {
                    rotate: 30
                }
            },
            yAxis: {
                type: 'value',
                name: '湿度(%)',
                axisLabel: {
                    formatter: '{value} %'
                }
            },
            series: [
                {
                    name: '平均湿度',
                    type: 'line',
                    data: avgHumidity,
                    markPoint: {
                        data: [
                            {type: 'max', name: '最大值'},
                            {type: 'min', name: '最小值'}
                        ]
                    }
                },
                {
                    name: '最高湿度',
                    type: 'line',
                    data: maxHumidity,
                    lineStyle: {
                        type: 'dashed'
                    }
                },
                {
                    name: '最低湿度',
                    type: 'line',
                    data: minHumidity,
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            ]
        };
        
        // 统计异常数据
        var normalCount = 0;
        var temperatureAbnormalCount = 0;
        var humidityAbnormalCount = 0;
        var bothAbnormalCount = 0;
        
        // 查询历史数据，统计异常情况
        var warehouseId = $('#warehouseSelect').val();
        var startDateTime = $('#startDateInput').val() + ' 00:00:00';
        var endDateTime = $('#endDateInput').val() + ' 23:59:59';
        var storageArea = $('#storageAreaSelect').val();
        var deviceId = $('#deviceIdSelect').val();
        
        // 构建查询参数
        var params = {
            warehouseId: warehouseId,
            startTime: startDateTime,
            endTime: endDateTime
        };
        
        if (storageArea) {
            params.storageArea = storageArea;
        }
        
        if (deviceId) {
            params.deviceId = deviceId;
        }
        
        $.ajax({
            url: '/warehouse/coldStorageMonitor/history/data',
            type: 'GET',
            data: params,
            success: function(res) {
                if (res.code === 200) {
                    var historyData = res.data;
                    
                    // 统计各状态的数量
                    historyData.forEach(function(item) {
                        if (item.status === '0') {
                            normalCount++;
                        } else if (item.status === '1') {
                            temperatureAbnormalCount++;
                        } else if (item.status === '2') {
                            humidityAbnormalCount++;
                        } else if (item.status === '3') {
                            bothAbnormalCount++;
                        }
                    });
                    
                    // 渲染异常统计图
                    var abnormalOption = {
                        title: {
                            text: '温湿度异常统计',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)'
                        },
                        legend: {
                            orient: 'horizontal',
                            bottom: 10,
                            data: ['正常', '温度异常', '湿度异常', '温湿度均异常']
                        },
                        series: [
                            {
                                name: '异常统计',
                                type: 'pie',
                                radius: ['40%', '70%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 10,
                                    borderColor: '#fff',
                                    borderWidth: 2
                                },
                                label: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: '18',
                                        fontWeight: 'bold'
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: [
                                    {value: normalCount, name: '正常', itemStyle: {color: '#28a745'}},
                                    {value: temperatureAbnormalCount, name: '温度异常', itemStyle: {color: '#ffc107'}},
                                    {value: humidityAbnormalCount, name: '湿度异常', itemStyle: {color: '#17a2b8'}},
                                    {value: bothAbnormalCount, name: '温湿度均异常', itemStyle: {color: '#dc3545'}}
                                ]
                            }
                        ]
                    };
                    
                    abnormalChart.setOption(abnormalOption);
                }
            }
        });
        
        temperatureChart.setOption(temperatureOption);
        humidityChart.setOption(humidityOption);
    }
}); 